package com.example.music_player

import android.app.Service
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Binder
import android.os.IBinder
import com.example.music_player.MusicFile
import com.example.music_player.data.AppDatabase
import com.example.music_player.data.PlayHistory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*

// MusicService: 音乐播放服务，负责音乐播放的核心功能
class MusicService : Service() {
    private lateinit var mediaPlayer: MediaPlayer        // 媒体播放器
    private var currentTrackIndex = 0                    // 当前播放曲目索引
    private val musicFiles = mutableListOf<MusicFile>()  // 音乐文件列表
    private var isPlaying = false                        // 播放状态
    
    // 播放模式枚举
    enum class PlayMode { 
        SEQUENTIAL,  // 顺序播放
        SHUFFLE,    // 随机播放
        REPEAT_ONE  // 单曲循环
    }
    private var currentPlayMode = PlayMode.SEQUENTIAL    // 当前播放模式
    private val random = java.util.Random()              // 随机数生成器
    
    private val binder = MusicBinder()                   // 服务绑定器
    
    // Binder类，用于Activity与Service通信
    inner class MusicBinder : Binder() {
        fun getService(): MusicService = this@MusicService
    }
    
    override fun onBind(intent: Intent): IBinder {
        return binder
    }
    
    // 服务创建时初始化
    override fun onCreate() {
        super.onCreate()
        mediaPlayer = MediaPlayer()
        currentPlayMode = loadPlayMode()
        setupMediaPlayer()
    }
    
    // 设置媒体播放器
    private fun setupMediaPlayer() {
        mediaPlayer.setOnCompletionListener {
            when (currentPlayMode) {
                PlayMode.SEQUENTIAL -> {
                    // 顺序播放模式：循环播放下一首
                    currentTrackIndex = (currentTrackIndex + 1) % musicFiles.size
                    playMusic(musicFiles[currentTrackIndex].uri)
                }
                PlayMode.SHUFFLE -> {
                    // 随机播放模式：随机播放一首不同的歌曲
                    if (musicFiles.size > 1) {
                        val currentIndex = currentTrackIndex
                        do {
                            currentTrackIndex = random.nextInt(musicFiles.size)
                        } while (currentTrackIndex == currentIndex && musicFiles.size > 1)
                        playMusic(musicFiles[currentTrackIndex].uri)
                    }
                }
                PlayMode.REPEAT_ONE -> {
                    // 单曲循环模式：重新播放当前歌曲
                    playMusic(musicFiles[currentTrackIndex].uri)
                }
            }
        }
    }
    
    // 播放状态变化监听接口
    interface OnPlaybackStateChangeListener {
        fun onSongChanged(songName: String?)            // 歌曲改变回调
        fun onPlayStateChanged(isPlaying: Boolean)      // 播放状态改变回调
    }

    private val listeners = mutableListOf<OnPlaybackStateChangeListener>()  // 监听器列表

    // 添加播放状态监听器
    fun addPlaybackStateChangeListener(listener: OnPlaybackStateChangeListener) {
        listeners.add(listener)
    }

    // 移除播放状态监听器
    fun removePlaybackStateChangeListener(listener: OnPlaybackStateChangeListener) {
        listeners.remove(listener)
    }

    // 通知歌曲变化
    private fun notifySongChanged() {
        val songName = getCurrentSongName()
        listeners.forEach { it.onSongChanged(songName) }
    }

    // 通知播放状态变化
    private fun notifyPlayStateChanged() {
        listeners.forEach { it.onPlayStateChanged(isPlaying) }
    }
    
    // 播放音乐
    private val playLock = Object()
    private var isPreparingMusic = false

    fun playMusic(uri: Uri) {
        synchronized(playLock) {
            if (isPreparingMusic) return  // 如果正在准备播放，则忽略新的播放请求
            
            try {
                isPreparingMusic = true
                mediaPlayer.reset()
                mediaPlayer.setDataSource(this, uri)
                mediaPlayer.prepareAsync()
                mediaPlayer.setOnPreparedListener {
                    mediaPlayer.start()
                    isPlaying = true
                    notifySongChanged()
                    notifyPlayStateChanged()
                    isPreparingMusic = false
                    
                    // 记录播放历史
                    savePlayHistory(uri)
                }
                mediaPlayer.setOnErrorListener { _, _, _ ->
                    isPreparingMusic = false
                    isPlaying = false
                    notifyPlayStateChanged()
                    true
                }
            } catch (e: Exception) {
                e.printStackTrace()
                isPreparingMusic = false
                isPlaying = false
                notifyPlayStateChanged()
            }
        }
    }
    
    // 播放下一首
    fun playNext() {
        if (musicFiles.isEmpty() || isPreparingMusic) return
        
        when (currentPlayMode) {
            PlayMode.SEQUENTIAL, PlayMode.REPEAT_ONE -> {
                currentTrackIndex = (currentTrackIndex + 1) % musicFiles.size
                playMusic(musicFiles[currentTrackIndex].uri)
            }
            PlayMode.SHUFFLE -> {
                if (musicFiles.size > 1) {
                    val currentIndex = currentTrackIndex
                    do {
                        currentTrackIndex = random.nextInt(musicFiles.size)
                    } while (currentTrackIndex == currentIndex && musicFiles.size > 1)
                    playMusic(musicFiles[currentTrackIndex].uri)
                }
            }
        }
    }
    
    // 播放上一首
    fun playPrevious() {
        if (musicFiles.isEmpty() || isPreparingMusic) return
        
        when (currentPlayMode) {
            PlayMode.SEQUENTIAL, PlayMode.REPEAT_ONE -> {
                currentTrackIndex = if (currentTrackIndex > 0) {
                    currentTrackIndex - 1
                } else {
                    musicFiles.size - 1
                }
                playMusic(musicFiles[currentTrackIndex].uri)
            }
            PlayMode.SHUFFLE -> {
                if (musicFiles.size > 1) {
                    val currentIndex = currentTrackIndex
                    do {
                        currentTrackIndex = random.nextInt(musicFiles.size)
                    } while (currentTrackIndex == currentIndex && musicFiles.size > 1)
                    playMusic(musicFiles[currentTrackIndex].uri)
                }
            }
        }
    }
    
    // 暂停播放
    fun pauseMusic() {
        if (mediaPlayer.isPlaying) {
            mediaPlayer.pause()
            isPlaying = false
            notifyPlayStateChanged()
        }
    }
    
    // 恢复播放
    fun resumeMusic() {
        if (!mediaPlayer.isPlaying) {
            mediaPlayer.start()
            isPlaying = true
            notifyPlayStateChanged()
        }
    }
    
    // 设置音乐列表
    fun setMusicList(list: List<MusicFile>) {
        musicFiles.clear()
        musicFiles.addAll(list)
    }
    
    // 获取当前播放位置
    fun getCurrentPosition(): Int = mediaPlayer.currentPosition
    // 获取音乐总时长
    fun getDuration(): Int = mediaPlayer.duration
    // 跳转到指定位置
    fun seekTo(position: Int) = mediaPlayer.seekTo(position)
    // 获取播放状态
    fun isPlaying(): Boolean = isPlaying
    
    // 设置播放模式
    fun setPlayMode(mode: PlayMode) {
        currentPlayMode = mode
        savePlayMode(mode)
    }
    
    // 获取当前播放模式
    fun getPlayMode(): PlayMode = currentPlayMode
    
    // 获取当前播放歌曲名称
    fun getCurrentSongName(): String? {
        return if (musicFiles.isNotEmpty() && currentTrackIndex < musicFiles.size) {
            musicFiles[currentTrackIndex].name
        } else {
            null
        }
    }
    
    // 服务销毁时释放资源
    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.release()
    }

    // 保存播放模式到偏好设置
    private fun savePlayMode(mode: PlayMode) {
        getSharedPreferences("MusicPreferences", Context.MODE_PRIVATE)
            .edit()
            .putString("playMode", mode.name)
            .apply()
    }

    // 从偏好设置加载播放模式
    private fun loadPlayMode(): PlayMode {
        val modeName = getSharedPreferences("MusicPreferences", Context.MODE_PRIVATE)
            .getString("playMode", PlayMode.SEQUENTIAL.name)
        return PlayMode.valueOf(modeName ?: PlayMode.SEQUENTIAL.name)
    }

    // 播放指定位置的音乐
    fun playMusicAtPosition(position: Int) {
        if (position >= 0 && position < musicFiles.size) {
            currentTrackIndex = position
            playMusic(musicFiles[position].uri)
        }
    }

    /**
     * 保存播放历史
     */
    private fun savePlayHistory(uri: Uri) {
        // 获取当前登录用户
        val username = applicationContext.getSharedPreferences(
            "UserPreferences", Context.MODE_PRIVATE
        ).getString("currentUsername", null) ?: return

        // 获取当前播放的音乐文件信息
        val currentMusic = musicFiles.getOrNull(currentTrackIndex)
        
        // 使用 MusicFile 中的名称而不是从 URI 解析
        val songName = currentMusic?.name ?: "未知歌曲"

        // 创建播放历史记录
        val playHistory = PlayHistory(
            username = username,
            songPath = uri.toString(),
            songName = songName,
            playTime = Date()
        )

        // 在协程中保存到数据库
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val database = AppDatabase.getDatabase(applicationContext)
                database.playHistoryDao().insertHistory(playHistory)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
} 